<template>
  <div class="app-container">
<!--    用量分析页面-->
    <el-row style="width: 100%;height: 100%;margin: 0;" :gutter="10">
      <!--区域数据-->
      <el-col :span="4" style="height: 100%;padding-left: 0;">
        <div style="background-color: #FFFFFF;height: 100%;padding: 10px;">
          <el-input :placeholder="filterTypeSelect === 'terminalName' ? '请输入设备名称进行查询' : '请输入设备编号进行查询'" v-model="filterText" class="input-with-select" size="mini">
            <el-select v-model="filterTypeSelect" slot="prepend" placeholder="请选择" style="width: 100px;">
              <el-option label="设备名称" value="terminalName"></el-option>
              <el-option label="设备编号" value="termianlId"></el-option>
            </el-select>
            <!--            <el-button slot="append" icon="el-icon-search" style="width: 40px;"></el-button>-->
          </el-input>
          <div style="height: 96%; max-height:96%;overflow-y: auto;margin-top: 10px;" class="treeCont">
          <el-tree
            :data="sheetsTreeList"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="code"
            :default-expanded-keys="defaultExpandedKeys"
            highlight-current
            v-loading="treeLoading"
            @node-click="handleNodeClick"
          >
            <template #default="{ node, data}">
              <div class="custom-tree-node"
                   style="display: flex;justify-content: center;align-items: center;font-size: 14px;">
                <span class="iconfont icon-a-jiafangzijianzhu icon-padding" v-if="data.deviceType === 0"></span>
                <span class="iconfont icon-loudong icon-padding" v-if="data.deviceType === 1"></span>
                <span class="iconfont icon-a-homezhuyefangzijia icon-padding" v-if="data.deviceType === 2"></span>
                <span class="iconfont icon-dabiao icon-padding" v-if="data.deviceType !== 0 && data.deviceType !== 1 && data.deviceType !== 2"></span>
                <span>{{ node.label }}</span>
                <span v-if="data.deviceCount!=null" class="device-count">({{data.deviceCount}})</span>
              </div>
            </template>
          </el-tree>
          </div>
        </div>
      </el-col>

      <!--大用户用量数据-->
      <el-col :span="20" style="height: 100%;background-color: #FFFFFF;">
        <el-row class="line-bottom" v-show="showSearch" style="margin: 10px 5px 5px;">
          <el-col :span="20">
            <el-form :model="queryParams" ref="queryForm" size="mini" v-show="showSearch" :rules="queryrules">
              <!-- <el-row>
                <el-col :span="20"> -->
              <div id="searchFilter" style="display: flex; flex-wrap: wrap">
                <el-form-item label="分析类型" label-width="80px">
                  <el-radio-group v-model="queryParams.dataType" size="mini" @change="dataTypeSelectChange">
                    <el-radio-button label="1">日用量</el-radio-button>
                    <el-radio-button label="2">月用量</el-radio-button>
                    <el-radio-button label="3">年用量</el-radio-button>
                  </el-radio-group>
                </el-form-item>
                <el-form-item label="时间间隔" prop="interval" v-if="queryParams.dataType === '1'" label-width="80px">
                  <el-select v-model="queryParams.interval" placeholder="请选择时间间隔" style="width: 100px;">
                    <el-option v-for="(item, index) of realIntervalList" :key="index" :label="item.value"
                               :value="item.key">{{ item.value }}
                    </el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="时间选择" prop="timevalue" label-width="80px">
                  <el-date-picker v-model="timevalue" type="datetimerange" range-separator="至"
                                  start-placeholder="开始日期"
                                  end-placeholder="结束日期" style="width: 82%;" v-if="queryParams.dataType === '1'"
                                  value-format="yyyy-MM-dd HH:mm:ss" :clearable="false"
                                  :default-time="['00:00:00', '23:59:59']"
                                  @change="handleQuery">
                  </el-date-picker>
                  <el-date-picker v-model="timevalue" type="daterange" range-separator="至" start-placeholder="开始日期"
                                  end-placeholder="结束日期" style="width: 55%;" v-if="queryParams.dataType === '2'"
                                  value-format="yyyy-MM-dd" :clearable="false"
                                  @change="handleQuery">
                  </el-date-picker>
                  <el-date-picker v-model="timevalue" type="monthrange" range-separator="至"
                                  start-placeholder="开始月份"
                                  end-placeholder="结束月份" style="width: 50%;" v-if="queryParams.dataType === '3'"
                                  value-format="yyyy-MM" :clearable="false"
                                  @change="handleQuery">
                  </el-date-picker>
                </el-form-item>
              </div>
            </el-form>
          </el-col>
          <el-col :span="4" align="right">
            <el-button v-show="collapseAble" type="text" size="mini" @click="shiftCollapseAble" class="text">
              <span>
                {{ fold ? '收起筛选' : '更多筛选' }}
              </span>
            </el-button>
            <el-button type="primary" icon="el-icon-search" @click="handleQuery" size="mini">查询</el-button>
            <el-button icon="el-icon-refresh" @click="resetQuery" size="mini">重置</el-button>
          </el-col>
        </el-row>
        <!-- <el-row>
          <RightDropdown :columns="columns"></RightDropdown>
        </el-row> -->
        <el-row>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="用量数据" name="history">
              <el-table ref="tableDay" key="tableDay" v-loading="loading" :data="dayDataList" size="mini" border
                        :height="getAvailableHeight"
                        :default-sort="defaultSort" @sort-change="handleSorterChange"
                        v-if="queryParams.dataType === '1'">
                <el-table-column v-for="(item, index) in dayColumns" :prop="item.dataIndex" align="center"
                                 :show-overflow-tooltip="true" :sortable="item.sortable" :sort-orders="item.sortOrder"
                                 :label="item.title" :key="index">
                </el-table-column>
              </el-table>

              <el-table ref="tableMonth" key="tableMonth" v-loading="loading" :data="monthDataList" size="mini" border
                        :height="getAvailableHeight"
                        :default-sort="defaultSort" @sort-change="handleSorterChange"
                        v-if="queryParams.dataType === '2'">
                <el-table-column v-for="(item, index) in monthColumns" :prop="item.dataIndex" align="center"
                                 :show-overflow-tooltip="true" :sortable="item.sortable" :sort-orders="item.sortOrder"
                                 :label="item.title" :key="index">
                </el-table-column>
              </el-table>

              <el-table ref="tableYear" key="tableYear" v-loading="loading" :data="yearDataList" size="mini" border
                        :height="getAvailableHeight"
                        :default-sort="defaultSort" @sort-change="handleSorterChange"
                        v-if="queryParams.dataType === '3'">
                <el-table-column v-for="(item, index) in yearColumns" :prop="item.dataIndex" align="center"
                                 :show-overflow-tooltip="true" :sortable="item.sortable" :sort-orders="item.sortOrder"
                                 :label="item.title" :key="index">
                </el-table-column>
              </el-table>

              <pagination :total="total"
                          :page.sync="queryParams.pageNum"
                          :limit.sync="queryParams.pageSize"
                          @pagination="getList"/>
            </el-tab-pane>
            <el-tab-pane label="图表展示" name="charts">
              <div id="main" ref="main" :style="getChartBoxStyle"></div>
            </el-tab-pane>
          </el-tabs>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listAreaTree } from '@/api/datastatistics/terminals/dosageStatics.js'
import {getTerminalDosageList, getPageList} from "@/api/datastatistics/terminals/dosageStatics.js"
import moment from 'moment'
import {getTwoTimeList, getTwoDayList, getTwoMonth,} from '@/utils/computeDays';
import * as echarts from 'echarts';

require('echarts/theme/macarons')
import {listTerminalsDbTree} from "@/api/record/terminalsdb";

export default {
  name: "DosageStaticsDb",
  data() {
    return {
      filterTypeSelect: 'terminalName',
      defaultExpandedKeys: [],
      screenHeight: null,
      // 总条数
      total: 0,
      // 图表数据
      echartsList: [],
      // tab名称
      activeName: 'history',
      // 折线图继承
      chartExtend: {
        // 标题
        title: {
          text: ''
        },
        grid: {
          top: '5%',
          left: '5%',
          right: '5%',
          bottom: '6%',
          containLabel: true,
        },
        // x轴
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [], // x轴坐标名称
        },
        // y轴
        yAxis: {
          //2022/10 /chuan 原：流量
          name: '用量(m³)',
          type: 'value',
          axisLabel: {
            formatter: '{value} m³'
          }
        },
        // 提示框，鼠标悬浮交互时的信息提示
        tooltip: {
          show: true,
          trigger: 'axis', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}
          }
        },
        legend: {
          data: ['正向用量', '反向用量', '净用量'],
          x: 'center',
          y: 'top',
          show: true,
          padding: 20
        },
        dataZoom: [{
          start: 0,
          end: 100,
          bottom: 10,
          type: 'slider',
          showDataShadow: false,
          handleIcon: 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '100%'
        }, {
          type: 'inside'
        }],
        // 指定图标的类型
        series: [],
      },
      // 实时时间间隔类型下拉
      realIntervalList: [
        {key: '1', value: '1小时',},
        {key: '2', value: '2小时',},
        {key: '4', value: '4小时',},
        {key: '6', value: '6小时',},
        {key: '12', value: '12小时',},
        {key: '24', value: '24小时',},
      ],
      size: 'small',
      collapseAble: false,
      fold: false,
      maxShow: '4',
      defaultProps: {
        children: "children",
        label: "label",
        isLeaf: "isLeaf",
      },
      // 实时数据图表横坐标
      realxAxis: [],
      // 日数据图表横坐标
      dayxAxis: [],
      // 月数据图表横坐标
      monthxAxis: [],
      // 区域树选项
      sheetsTreeList: [],
      // 区域名称
      keyWordName: '',
      // 树状态
      treeVisibale: true,
      // 遮罩层
      loading: true,
      treeLoading: true,
      // 显示搜索条件
      showSearch: true,
      // 查询参数
      // location_nb: '',
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        interval: '1',
        dataType: '1',
        location_nb: '',
        startTime: '',
        endTime: '',
        toUnderScore: false,
        systemFlag: null,
        loginUserId: null,
      },
      // 表单校验
      queryrules: {
        // timevalue: [
        //   { type: 'date', required: true, message: "时间不能为空", trigger: "change" }
        // ],
        // interval: [
        //   { required: true, message: "时间间隔不能为空", trigger: "blur" }
        // ],
      },
      // 数据表格数据
      dayDataList: [],
      // 表头数据
      dayColumns: [
        {
          title: '采集时间',
          dataIndex: 'readDateN',
          width: 200,
          sortable: 'custom',
          sortOrder: ['ascending', 'descending']
        },
        {title: '正向用量(m³)', dataIndex: 'readDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']},
        {title: '反向用量(m³)', dataIndex: 'reverseDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']},
        {title: '净用量(m³)', dataIndex: 'totalDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']}
      ],
      // 数据表格数据
      monthDataList: [],
      monthColumns: [
        {
          title: '数据日期',
          dataIndex: 'readDateDay',
          width: 200,
          sortable: 'custom',
          sortOrder: ['ascending', 'descending']
        },
        {title: '正向用量(m³)', dataIndex: 'readDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']},
        {title: '反向用量(m³)', dataIndex: 'reverseDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']},
        {title: '净用量(m³)', dataIndex: 'totalDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']}
      ],
      // 数据表格数据
      yearDataList: [],
      yearColumns: [
        {
          title: '数据月份',
          dataIndex: 'readDateMonth',
          width: 200,
          sortable: 'custom',
          sortOrder: ['ascending', 'descending']
        },
        {title: '正向用量(m³)', dataIndex: 'readDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']},
        {title: '反向用量(m³)', dataIndex: 'reverseDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']},
        {title: '净用量(m³)', dataIndex: 'totalDosage', sortable: 'custom', sortOrder: ['ascending', 'descending']}
      ],
      // 默认排序
      defaultSort: {prop: 'readDateN', order: 'descending'},
      showtime: true,
      // 时间选择
      timevalue: [moment(new Date()).format('YYYY-MM-DD 00:00:00'), moment(new Date()).format('YYYY-MM-DD 23:59:59')],
      filterText: '',
      myChart: undefined,
    };
  },
  created() {
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 270
    },
    getChartBoxStyle() {
      return {width: '100%', height: (this.screenHeight - 250) + 'px'}
    },
    loginUserId() {
      return this.$store.state.user.userId
    },
    systemFlag() {
      return this.$store.state.user.systemFlag
    }
  },
  mounted() {
    this.tip()
    this.initEchart()
    this.getTreeList()
    // 通过最大显示个数控制展开/折叠
    if (this.maxShow > 0) {
      this.minShowControl()
    }
  },
  watch: {
    // 根据名称筛选区域树
    filterText(val) {
      this.$refs.tree.filter(val);
    }
  },
  methods: {
    /** 排序触发事件 */
    handleSorterChange({column, prop, order}) {
      this.queryParams.orderByColumn = prop
      this.queryParams.isAsc = order
      this.getList()
    },
    /** 检查设置排序字段 */
    checkSortColumn() {
      if (!this.queryParams.orderByColumn) {
        this.queryParams.orderByColumn = this.defaultSort.prop
        this.queryParams.isAsc = this.defaultSort.order
      }
    },
    // 切换tab
    handleClick() {
      if (this.activeName === 'charts') {
        this.$nextTick(() => {
          this.initEchart()
        })
      }
    },
    // 初始化echarts
    initEchart() {
      if (this.myChart) {
        this.myChart.dispose()
      }
      this.myChart = echarts.init(this.$refs.main)
      // this.handleData()
      this.myChart.setOption(this.chartExtend, true)
      this.myChart.resize()
      window.addEventListener('resize', () => {
        this.myChart.resize()
      })
    },
    // 重置图表
    resetEchart() {
      this.chartExtend = {
        // 标题
        title: {
          text: ''
        },
        grid: {
          top: '5%',
          left: '5%',
          right: '5%',
          bottom: '6%',
          containLabel: true,
        },
        // x轴
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: [], // x轴坐标名称
        },
        // y轴
        yAxis: {
          //2022/10 /chuan 原：流量
          name: '用量(m³)',
          type: 'value',
          axisLabel: {
            formatter: '{value} m³'
          }
        },
        // 提示框，鼠标悬浮交互时的信息提示
        tooltip: {
          show: true,
          trigger: 'axis', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {}
          }
        },
        legend: {
          data: ['正向用量', '反向用量', '净用量'],
          x: 'center',
          y: 'top',
          show: true,
          padding: 20
        },
        dataZoom: [{
          start: 0,
          end: 100,
          bottom: 10,
          type: 'slider',
          showDataShadow: false,
          handleIcon: 'path://M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z',
          handleSize: '100%'
        }, {
          type: 'inside'
        }],
        // 指定图标的类型
        series: []
      }
    },
    // 渲染图表
    renderChart() {
      let days = []
      let startTime = this.queryParams.startTime
      let endTime = this.queryParams.endTime
      if (this.queryParams.dataType === '1') {
        let newStartTime = moment(startTime).format('YYYY-MM-DD HH:mm:ss')
        let newEndTime = moment(endTime).format('YYYY-MM-DD HH:mm:ss')
        days = getTwoTimeList(newStartTime, newEndTime)
        days.sort((a,b)=>{return a-b});
        this.chartExtend.xAxis.data = days
      } else if (this.queryParams.dataType === '2') {
        let newStartTime = moment(startTime).format('YYYY-MM-DD')
        let newEndTime = moment(endTime).format('YYYY-MM-DD')
        days = getTwoDayList(newStartTime, newEndTime)
        days.sort((a,b)=>{return a-b});
        this.chartExtend.xAxis.data = days
      } else if (this.queryParams.dataType === '3') {
        let newStartTime = moment(startTime).format('YYYY-MM')
        let newEndTime = moment(endTime).format('YYYY-MM')
        days = getTwoMonth(newStartTime, newEndTime)
        days.sort((a,b)=>{return a-b});
        this.chartExtend.xAxis.data = days
      }
      this.initEchart()
    },
    // 获取纵坐标
    handleData() {
      let datalist = this.echartsList
      let xData = []
      let readlistitem = []
      let reverselistitem = []
      let totallistitem = []
      for (var i = 0; i < datalist.length; i++) {
        if (this.queryParams.dataType == '1') {
          xData.push(datalist[i].readDateN);
          xData.sort((a,b)=>{return Date.parse(a)- Date.parse(b)});
          readlistitem.push([datalist[i].readDateN, datalist[i].readDosage]);
          reverselistitem.push([datalist[i].readDateN, datalist[i].reverseDosage]);
          totallistitem.push([datalist[i].readDateN, datalist[i].totalDosage]);
        } else if (this.queryParams.dataType == '2') {
          xData.push(datalist[i].readDateDay);
          xData.sort((a,b)=>{return Date.parse(a)- Date.parse(b)});
          readlistitem.push([datalist[i].readDateDay, datalist[i].readDosage]);
          reverselistitem.push([datalist[i].readDateDay, datalist[i].reverseDosage]);
          totallistitem.push([datalist[i].readDateDay, datalist[i].totalDosage]);
        } else if (this.queryParams.dataType == '3') {
          xData.push(datalist[i].readDateMonth);
          xData.sort((a,b)=>{return Date.parse(a)- Date.parse(b)});
          readlistitem.push([datalist[i].readDateMonth, datalist[i].readDosage]);
          reverselistitem.push([datalist[i].readDateMonth, datalist[i].reverseDosage]);
          totallistitem.push([datalist[i].readDateMonth, datalist[i].totalDosage]);
        }
      }
      let seriesItem = {
        name: '正向用量', // 系列名称
        type: 'line', // 类型：线
        smooth: true,
        data: readlistitem, // 数据
        markPoint: {
          // 特殊标注文字v/
          label: {
            normal: {
              show: true,
              //position: 'top', // 文字位置
              // 显示的文字
              formatter: '{b}：{c}',
            }
          },
          // 触发操作
          tooltip: {
            show: true, // 是否显示
            formatter: '{b}：{c}', // 内容格式器 a（系列名称），b（类目值），c（数值）, d（无）
            trigger: 'item', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
          },
        },
        // 折线图圆点
        label: {
          normal: {
            show: false,
            formatter: '{c}',
            textStyle: {
              color: '#000' // 文字颜色
            }
          }
        },
      }
      let readSeriesItem = {
        name: '反向用量', // 系列名称
        type: 'line', // 类型：线
        smooth: true,
        data: reverselistitem, // 数据
        markPoint: {
          // 特殊标注文字v/
          label: {
            normal: {
              show: true,
              //position: 'top', // 文字位置
              // 显示的文字
              formatter: '{b}：{c}',
            }
          },
          // 触发操作
          tooltip: {
            show: true, // 是否显示
            formatter: '{b}：{c}', // 内容格式器 a（系列名称），b（类目值），c（数值）, d（无）
            trigger: 'item', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
          },
        },
        // 折线图圆点
        label: {
          normal: {
            show: false,
            formatter: '{c}',
            textStyle: {
              color: '#000' // 文字颜色
            }
          }
        },
      }
      let totalSeriesItem = {
        name: '净用量', // 系列名称
        type: 'line', // 类型：线
        smooth: true,
        data: totallistitem, // 数据
        markPoint: {
          // 特殊标注文字v/
          label: {
            normal: {
              show: true,
              //position: 'top', // 文字位置
              // 显示的文字
              formatter: '{b}：{c}',
            }
          },
          // 触发操作
          tooltip: {
            show: true, // 是否显示
            formatter: '{b}：{c}', // 内容格式器 a（系列名称），b（类目值），c（数值）, d（无）
            trigger: 'item', // 触发类型，默认数据触发，见下图，可选为：'item' | 'axis'
          },
        },
        // 折线图圆点
        label: {
          normal: {
            show: false,
            formatter: '{c}',
            textStyle: {
              color: '#000' // 文字颜色
            }
          }
        },
      }
      this.chartExtend.xAxis.data = xData
      this.chartExtend.series.push(seriesItem);
      this.chartExtend.series.push(readSeriesItem);
      this.chartExtend.series.push(totalSeriesItem);
      this.initEchart()
    },
    // 图表数据处理
    getEchartsData() {
      getTerminalDosageList(this.queryParams).then(response => {
        if (response.code === 200) {
          this.echartsList = response.data
          this.renderChart()
          this.handleData()
        }
      });
    },
    // 获取表格数据
    getList() {
      this.checkSortColumn()
      this.loading = true;
      getPageList(this.queryParams).then(response => {
        this.loading = false;
        if (response.code === 200) {
          if (this.queryParams.dataType === '1') {
            this.dayDataList = response.rows
          } else if (this.queryParams.dataType === '2') {
            this.monthDataList = response.rows
          } else {
            this.yearDataList = response.rows
          }
          this.total = response.total
        }
      });
    },
    handleNodeClick(data) {
      this.handleQuery()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.resetEchart()
      let choiceCheck = this.$refs.tree.getCurrentNode()
      if (choiceCheck && choiceCheck.deviceType === 3) {
        this.queryParams.location_nb = choiceCheck.locationNb
        this.queryParams.startTime = this.timevalue[0]
        this.queryParams.endTime = this.timevalue[1]
        this.getEchartsData()
        this.getList()
      } else {
        this.$modal.msgWarning("请选择一个设备!")
      }
    },
    // 重置表单
    resetQuery() {
      this.timevalue = [moment(new Date()).format('YYYY-MM-DD 00:00:00'), moment(new Date()).format('YYYY-MM-DD 23:59:59')]
      this.queryParams = {
        pageNum: 1,
        pageSize: 20,
        interval: '1',
        dataType: '1',
        location_nb: '',
        startTime: moment(new Date()).format('YYYY-MM-DD 00:00:00'),
        endTime: moment(new Date()).format('YYYY-MM-DD 23:59:59'),
        toUnderScore: false
      }
      this.$refs.tree.setCheckedNodes([]);
      this.$refs.tree.setCurrentKey(null);
      this.chartExtend.series = []
      this.dataList = []
      this.initEchart()
      this.handleQuery()
    },
    // 展开折叠按钮
    shiftCollapseAble() {
      this.fold = !this.fold
      this.minShowControl()
    },
    // 通过maxShow控制元素显示/折叠
    minShowControl() {
      const group = window.document.querySelectorAll(`#searchFilter .el-form-item.el-form-item--${this.size}`)
      const len = group?.length ? group?.length - 1 : 0
      if (this.maxShow < len) {
        group.forEach((item, index) => {
          if (index > this.maxShow - 1 && index < len) {
            item.hidden = !this.fold
          }
        })
        this.collapseAble = true
      } else {
        this.collapseAble = false
      }
    },
    // 筛选节点
    filterNode(value, data) {
      if(!value){
        return true
      }else{
        if(this.filterTypeSelect === 'terminalName'){
          return data.label.indexOf(value) !== -1;
        }else {
          if(data.deviceType === 3){
            return data.locationNb.indexOf(value) !== -1;
          }
        }
      }
    },
    /** 查询区域下拉树结构 */
    getTreeList() {
      // this.treeLoading = true
      // this.areaOptions = []
      // listTerminalsDbTree({}).then(res => {
      //   if (res.code === 200) {
      //     this.areaOptions.push(res.data)
      //     this.defaultExpandedKeys = [this.areaOptions[0].code];
      //     this.treeLoading = false
      //   }
      // })
      this.treeLoading = true
      this.sheetsTreeList = []
      listAreaTree().then(res => {
        if (res.code === 200) {
          if (res.code === 200) {
            if(res.data.id === 0) {
              this.sheetsTreeList.push(...res.data.children) // 没有返回termianlId
            }else {
              this.sheetsTreeList.push(res.data)
            }
            if(this.defaultExpandedKeys.length){
              this.defaultExpandedKeys = [this.sheetsTreeList[0].code]
            }
            this.treeLoading = false
          }
        }
      })
    },
    // 切换类型
    dataTypeSelectChange() {
      let now = new Date();
      let table
      this.timevalue = [moment(now).format('YYYY-MM-DD 00:00:00'), moment(now).format('YYYY-MM-DD 23:59:59')];
      switch (this.queryParams.dataType) {
        // 实时数据
        case '1':
          this.defaultSort.prop = 'readDateN'
          table = this.$refs.tableDay
          this.timevalue = [
            moment(this.timevalue[0]).format('YYYY-MM-DD 00:00:00'),
            moment(this.timevalue[1]).format('YYYY-MM-DD 23:59:59')
          ]
          break;
        // 日报表
        case '2':
          this.defaultSort.prop = 'readDateDay'
          table = this.$refs.tableMonth
          this.timevalue = [
            moment(this.timevalue[0]).subtract(5, "days").format('YYYY-MM-DD'),
            moment(this.timevalue[1]).subtract(1, "days").format('YYYY-MM-DD')
          ]
          break;
        // 月报表
        case '3':
          this.defaultSort.prop = 'readDateMonth'
          table = this.$refs.tableYear
          this.timevalue = [
            moment(this.timevalue[0]).subtract(3, "months").format('YYYY-MM'),
            moment(this.timevalue[1]).subtract(1, "months").format('YYYY-MM')
          ]
          break;
      }
      this.queryParams.orderByColumn = this.defaultSort.prop
      this.queryParams.isAsc = this.defaultSort.order
      this.$nextTick(() => {
        table.doLayout()
        this.$forceUpdate()
      })
    },
    // 页面提示信息
    tip() {
      this.$modal.msgWarning("请选择一个设备查看数据!")
      this.loading = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.el-picker-panel__footer .el-picker-panel__link-btn.el-button--text {
  display: none;
}
//::v-deep .el-tabs__item.is-active {
//  color: rgb(255, 255, 255);
//  background-color: #409eff !important;
//}

#mapContent {
  width: 100%;
  margin: 0 auto;
  height: 500px;
}
// 设置本身箭头为隐藏状态
::v-deep .el-tree-node__expand-icon {
  width: 20px;
  padding: 0;
  margin: 5px 0;

  svg {
    display: none;
    width: 0;
  }
}

// 虚线所需样式
::v-deep .treeCont {
  .el-tree-node{
    width: fit-content;
  }
  .el-tree > .el-tree-node:before {
    //border-top: none;
    padding-left: 0px;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
  }

  .el-tree-node__content {
    padding-left: 5px !important;
  }

  .el-tree-node__children {
    //overflow: visible !important;
    .el-tree-node {
      position: relative;
      padding-left: 5px;
    }
  }

  //节点有间隙，隐藏掉展开按钮就好了,如果觉得空隙没事可以删掉
  .el-tree-node__expand-icon.is-leaf {
    width: 4px;
  }

  .el-tree-node__children {
    padding-left: 18px;
  }

  .el-tree-node :last-child:before {
    height: 17px;
  }

  .el-tree > .el-tree-node:before {
    border-left: none;
  }

  .el-tree > .el-tree-node:after {
    border-top: none;
    top: 25px;
    width: 0px;
  }

  .el-tree-node:before {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:after {
    content: "";
    left: -4px;
    position: absolute;
    right: auto;
    border-width: 1px;
  }

  .el-tree-node:before {
    border-left: 1px dashed #c0c4cc;
    height: 100%;
    top: -3px;
    width: 1px;
  }

  .el-tree-node:after {
    border-top: 1px dashed #c0c4cc;
    height: 0px;
    top: 13px;
    width: 16px;
  }
}

// 默认三角行换成加减号
::v-deep .treeCont {
  .el-tree-node__content > .el-tree-node__expand-icon {
    width: 16px;
    //width: 0px;
    padding: 0px;
    font-size: 16px !important;
    margin-right: 5px; //新增
  }

  .el-tree .el-tree-node__expand-icon.expanded {
    -webkit-transform: rotate(0deg);
    transform: rotate(0deg);
  }

  //有子节点 且未展开
  .el-tree .el-tree-node__expand-icon:before {
    background: url('../../../assets/images/jia.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  .custom-tree-node .el-icon svg {
    display: block !important;
    color: #000;
  }

  //有子节点 且已展开
  .el-tree .el-tree-node__expand-icon.expanded:before {
    background: url('../../../assets/images/jian.png') no-repeat;
    content: "";
    display: block;
    width: 20px;
    height: 20px;
    font-size: 20px;
    background-size: 100% 100%;
  }

  //没有子节点
  .el-tree .el-tree-node__expand-icon.is-leaf::before {
    background: none;
    content: "";
    display: block;
    width: 20px;
    height: 20px ;
    font-size: 20px;
    background-size: 100% 100%;
  }
}
</style>
